package cn.itcast.work.service.category;


import cn.itcast.work.dao.category.ArticleSearch;
import cn.itcast.work.pojo.Article;
import cn.itcast.work.pojo.ArticleCategory;
import cn.itcast.work.pojo.Text;
import cn.itcast.work.pojo.User;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * * @author: Mao Wanting
 * * @date: 2024/6/11
 * *description:收藏夹的事务处理层
 **/
@Slf4j
@Service("CategoryService")
public class CategoryService {

    @Autowired
    private ArticleSearch articleSearch;


    //相关操作之后的刷新处理
    @Transactional
    public Map<ArticleCategory, List<Text>> showCategory(User user, HttpSession httpSession) {
        Map<ArticleCategory, List<Text>> map = selectAll(user);
        httpSession.setAttribute("category", map);
        return map;
    }

    //得到用户id
    //todo添加进工具类中？
    public int selectUserId(User user) {
        log.info("[service]:查询用户id");
        return articleSearch.selectUserIdByName(user);

    }

    /**
     * 1.添加用户+添加一个默认收藏夹
     */
    @Transactional
    public String addDefaultCategory(User user) {
        ArticleCategory articleCategory = new ArticleCategory();
        articleCategory.setCategoryname("默认收藏夹");
        articleCategory.setIntroduction("这个人很懒，什么也没有留下");

        int result_category = articleSearch.insertCategoryByUser(user, articleCategory);
        if (result_category == 1) {
            return "成功为你创建了一个收藏夹";
        } else {
            return "创建默认收藏夹失败";
        }
    }


    /**
     * 2.添加一个收藏夹
     */
    @Transactional
    public String addCategory(User user, ArticleCategory category) {
        int result = articleSearch.insertCategoryByUser(user, category);
        if (result > 0) {
            return "增加收藏夹成功";
        } else {
            return "增加失败";
        }
    }


    /**
     * 3.添加文章进已有收藏夹
     */
    @Transactional
    public Map<String, Object> addArticle(User user, Text text, ArticleCategory articleCategory) {
        Map<String, Object> JsonStr = new HashMap<>();
        try {
            //判断一下该文章是否被收藏了
            //通过用户id，收藏夹id能否查出来article的id
            Integer isCollect = articleSearch.selectCollection(user.getId(), articleSearch.selectArticleIdByTest(text));
            if (isCollect > 0) {
                JsonStr.put("result", 0);
                JsonStr.put("message", "该文章已被收藏，无法再收藏");
                return JsonStr;
            } else {
                Article article = new Article();
                article.setArticleid(articleSearch.selectArticleIdByTest(text));//得到text_id
                articleCategory.setId(articleSearch.test(articleCategory, user));//得到category_id
                int result = articleSearch.insertArticleByUserCategory(user, article, articleCategory);
                if (result > 0) {
                    JsonStr.put("result", 1);
                    JsonStr.put("message", "收藏成功");
                    return JsonStr;
                } else {
                    JsonStr.put("result", 0);
                    JsonStr.put("message", "收藏失败");
                    return JsonStr;
                }
            }
        } catch (Exception e) {
            log.error("[service]:收藏出错,{}", e.getMessage());
            JsonStr.put("result", 0);
            JsonStr.put("message", "出错了");
            return JsonStr;
        }


    }


    /**
     * 删除收藏夹+收藏夹里的文章
     */
    @Transactional
    public String deleteCategoryAll(User user, ArticleCategory articleCategory) {


        int result_article = articleSearch.deleteByUserCategory(user, articleCategory);//首先删除掉收藏夹里的文章

        int result_category = articleSearch.deleteAllByUserCategory(user, articleCategory);//再删除收藏夹

        if (result_category > 0) {
            return "删除收藏夹成功";

        } else {
            return "删除失败";
        }
    }


    /**
     * 移除收藏中的单个文章
     */
    @Transactional
    public String deleteArticle(User user, ArticleCategory articleCategory, Text text) {


        Article article1 = articleSearch.selectArticleByTest(user, text);
        System.out.println(article1);

        int result_delete_article = articleSearch.deleteByArticle(user, articleCategory, article1);

        if (result_delete_article > 0) {

            return "移除文章成功";

        } else {

            return "移除文章失败";
        }
    }


    /**
     * 清空收藏夹
     */
    @Transactional
    public String deleteAllArticles(User user, ArticleCategory articleCategory) {

        int result = articleSearch.deleteByUserCategory(user, articleCategory);
        if (result == 0) {

            return "收藏夹为空";
        } else if (result > 0) {

            return "清空收藏夹成功";

        } else {

            return "清空失败";
        }
    }


    //修改

    /**
     * 修改收藏夹名称
     */
    @Transactional
    public String updateCategory(User user, ArticleCategory articleCategory, String newName) {

        int result = articleSearch.updateCategoryName(user, articleCategory, newName);
        if (result > 0) {

            return "修改成功";

        } else {

            return "修改失败";
        }
    }


    //查询

    /**
     * 获取收藏夹
     */
    @Transactional
    public List<ArticleCategory> selectCategory(User user, ArticleCategory articleCategory) {

        List<ArticleCategory> articleCategories = articleSearch.selectCategoryByUser(user);
        if (!articleCategories.isEmpty()) {

            return articleCategories;
        } else {

            return new ArrayList<>();
        }
    }

    /**
     * 查出所有收藏夹+收藏的文章（可能会存在一篇文章收藏在多个文件夹中，然后出现异常）
     */
    @Transactional
    public Map<ArticleCategory, List<Text>> selectAll(User user) {

        Map<ArticleCategory, List<Text>> articleCategoryListMap = new HashMap<>();
        List<ArticleCategory> articleCategoryList = articleSearch.selectCategoryByUser(user);//可以查出收藏夹的集合

        for (ArticleCategory category : articleCategoryList) {

            List<Article> articles = articleSearch.selectArticleByUserCategory(user, category);//得到article的id

            List<Text> texts = new ArrayList<>();

            for (Article article : articles) {

                Text text = articleSearch.selectTextsByArticle(user, article);//因为想法不同，需要将article切换成text
                texts.add(text);
            }

            articleCategoryListMap.put(category, texts);
        }

        System.out.println("查询出来的用户的收藏夹集合为:" + articleCategoryListMap);

        return articleCategoryListMap;//返回收藏夹以及收藏的文章
    }

    /**
     * 根据text的title查出id，得到article的id
     *
     * @param text
     * @return result
     */
    public int selectArticleId(Text text) {
        int result = articleSearch.selectArticleIdByTest(text);
        return result;//得到article的id
    }


}
